<template>
  <div class="form-container">
    <div class="form-header">
      <h2>公司信息编辑</h2>
    </div>

    <el-form :model="formData" label-width="100px">
      <el-form-item label="公司名称">
        <el-input v-model="formData.name" style="width: 300px" />
      </el-form-item>

      <el-form-item label="联系电话">
        <el-input v-model="formData.phone" style="width: 300px" />
      </el-form-item>

      <el-form-item label="公司邮箱">
        <el-input v-model="formData.email" style="width: 300px" />
      </el-form-item>

      <el-form-item label="公司简介">
        <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            style="width: 500px"
        />
      </el-form-item>

      <el-form-item label="公司图片">
        <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleCompanyImageChange"
            :on-remove="() => handleRemove('image')"
            :on-preview="handlePictureCardPreview"
            :file-list="companyImageList"
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">建议尺寸: 800x400px，大小不超过2MB</div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="公司二维码">
        <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleQrCodeChange"
            :on-remove="() => handleRemove('qrcode')"
            :on-preview="handlePictureCardPreview"
            :file-list="qrCodeList"
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">建议尺寸: 300x300px，大小不超过1MB</div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSubmit" :loading="loading">保存修改</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>

    <el-dialog v-model="dialogVisible">
      <img :src="dialogImageUrl" alt="Preview Image" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue';
import {Plus} from '@element-plus/icons-vue';
import axios from 'axios';
import {ElMessage} from 'element-plus';

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  phone: '',
  email: '',
  description: '',
  image: '',
  qrcode: ''
});

// 图片相关状态
const companyImageList = ref([]);
const qrCodeList = ref([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const loading = ref(false);

// 组件挂载时加载公司信息
onMounted(() => {
  fetchCompanyInfo();
});

// 获取公司信息
const fetchCompanyInfo = async () => {
  try {
    const response = await axios.get('/api/company/AllData');
    const {data} = response.data; // 解构出data字段

    // 填充表单数据
    Object.assign(formData, {
      id: data.id,
      name: data.name,
      phone: data.phone,
      email: data.email,
      description: data.description,
      image: data.image,
      qrcode: data.qrcode
    });

    // 设置图片预览
    companyImageList.value = data.image ? [{
      name: 'company-image',
      url: data.image
    }] : [];

    qrCodeList.value = data.qrcode ? [{
      name: 'company-qrcode',
      url: data.qrcode
    }] : [];

  } catch (error) {
    ElMessage.error('获取公司信息失败: ' + error.message);
  }
};

// 处理公司图片上传
const handleCompanyImageChange = (file, fileList) => {
  if (fileList.length > 1) {
    fileList.splice(0, 1);
  }
  companyImageList.value = fileList;
  formData.image = file.raw; // 存储文件对象用于上传
};

// 处理二维码上传
const handleQrCodeChange = (file, fileList) => {
  if (fileList.length > 1) {
    fileList.splice(0, 1);
  }
  qrCodeList.value = fileList;
  formData.qrcode = file.raw; // 存储文件对象用于上传
};

// 删除文件
const handleRemove = (type) => {
  if (type === 'image') {
    formData.image = '';
    companyImageList.value = [];
  } else if (type === 'qrcode') {
    formData.qrcode = '';
    qrCodeList.value = [];
  }
};

// 预览图片
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  try {
    loading.value = true;

    const formDataToSend = new FormData();

    // 添加表单数据
    for (const key in formData) {
      if (formData[key] !== null && formData[key] !== undefined) {
        formDataToSend.append(key, formData[key]);
      }
    }

    // 发送更新请求
    const response = await axios.put('/api/company', formDataToSend, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    ElMessage.success(response.data.message || '公司信息更新成功');
    // 重新加载最新数据
    await fetchCompanyInfo();

  } catch (error) {
    console.error('Error:', error);
    ElMessage.error('更新失败: ' + (error.response?.data?.message || error.message));
  } finally {
    loading.value = false;
  }
};

// 取消修改
const handleCancel = () => {
  // 重新加载原始数据
  fetchCompanyInfo();
  ElMessage.info('已取消修改');
};
</script>

<style scoped>
.form-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-header {
  margin-bottom: 30px;
  text-align: center;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 7px;
}
</style>
